import { chunkArray } from "../utils";
import type { FormatSaveParamsFn, GetProductBySkuMapFn } from "../type";
import { ACTION_TYPE, AGAIN_VALUE_LIST } from "@/constants/actionType";

// 列表名接口
function getPageDataUrl() {
  return `${location.origin}/dpas-api-prefix/dpas/discuss/bargain_page`;
}
// 同意建议价接口
function getDoAgreeToNegotiateUrl() {
  return `${location.origin}/dpas-api-prefix/dpas/discuss/batch_handle_cost_discuss`;
}

// 获取当前页数
function getCurrentPage() {
  return Number(
    document.querySelector(".so-pagination-current")?.textContent || 1
  );
}

// 获取PageSize
function getPageSize() {
  const pageSizeText =
    document.querySelector(".so-select-result")?.textContent || "";
  return Number(pageSizeText.match(/^\d+/)?.[0] || 10);
}

// 获取总页数
function getTotalPageSize() {
  const endPageElement = document
    .querySelector(".so-pagination-links")
    ?.querySelector(".so-pagination-item:nth-last-child(2)");

  return Number(endPageElement?.textContent || 0);
}

// 格式化列表数据
function formatListDataToMap({
  data,
  skuCodeList,
  productBySkuAndCostPriceMap,
  productBySkuCurrencyMap,
}: {
  data: any[];
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
  productBySkuCurrencyMap: any;
}) {
  return data.reduce((obj, dataItem: any) => {
    const { bargain_sn, sku_cost_prices, document_sn, skc_name } = dataItem;
    if (bargain_sn && document_sn) {
      obj[bargain_sn] = {
        bargain_sn,
        document_sn,
        skuPriceMap: {},
        skc_name,
        discuss_step: 1,
      };
      const skuCostPrices = sku_cost_prices || [];
      skuCostPrices.forEach((skuItem: any) => {
        const { sku_code, suggest_cost_price, cost_price_histories } = skuItem;
        obj[bargain_sn].skuPriceMap[sku_code] = suggest_cost_price;
        skuCodeList.push(sku_code);
        const costPriceHistoriesLength = cost_price_histories?.length || 0;
        if (costPriceHistoriesLength) {
          obj[bargain_sn].discuss_step = costPriceHistoriesLength
          productBySkuAndCostPriceMap[sku_code] =
            cost_price_histories?.[costPriceHistoriesLength - 1]?.cost_price;
          productBySkuCurrencyMap[sku_code] =
            cost_price_histories?.[costPriceHistoriesLength - 1]?.currency;
        }
      });
    }

    return obj;
  }, {});
}

// 获取商品列表中的信息
const getProductBySkuMap: GetProductBySkuMapFn = async ({
  pageNum = 1,
  pageSize = 10,
  skuCodeList = [],
  productBySkuAndCostPriceMap = {},
  productBySkuCurrencyMap = {},
}) => {
  const pageDataUrl = getPageDataUrl();
  const response = await fetch(
    `${pageDataUrl}?page_num=${pageNum}&page_size=${pageSize}`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ bargain_status: 1 }),
    }
  ).then((res) => res.json());
  const data = response?.info?.data || [];
  return formatListDataToMap({
    data,
    skuCodeList,
    productBySkuAndCostPriceMap,
    productBySkuCurrencyMap,
  });
};

// 操作时格式化数据
const formatSaveParams: FormatSaveParamsFn = ({
  productBySkuMap,
  skuPurchasePriceMap,
  multiplier,
  actionType,
  productBySkuCurrencyMap,
  productBySkuAndCostPriceMap,
}) => {
  const paramList: any[] = [];
  let successTotal = 0;
  let skipCount = 0;
  for (const key of Object.keys(productBySkuMap)) {
    const { bargain_sn, document_sn, skuPriceMap, skc_name, discuss_step } =
      productBySkuMap[key];
    let isSkip = false;
    const sku_cost_info_list: any = [];
    for (const skuCode of Object.keys(skuPriceMap)) {
      const hasErpData = skuCode in skuPurchasePriceMap;
      if (!hasErpData) {
        isSkip = true;
        break;
      }
      const skuPriceNumber = Number(skuPriceMap[skuCode]);
      const contrastNumber =
        Number(skuPurchasePriceMap[skuCode]) * Number(multiplier);
      if (actionType === ACTION_TYPE.AGREE) {
        // 同意建议价, 如果"核算源价" x "倍率"比"平台建议价"小则符合同意条件
        if (contrastNumber < skuPriceNumber) {
          // 执行
        } else {
          // 否则跳过
          isSkip = true;
        }
      } else if (actionType === ACTION_TYPE.REFUSE) {
        // 拒绝建议价, 如果"核算源价" x "倍率"比"平台建议价"大则符合拒绝条件
        if (contrastNumber > skuPriceNumber) {
          // 执行
        } else {
          isSkip = true;
          // 否则跳过
        }
      } else if (AGAIN_VALUE_LIST.includes(actionType)) {
        // 重新报价,无需校验,直接用 "核算源价" x/- "倍率" 去重新报价
        const skuCodeCurrency = productBySkuCurrencyMap[skuCode];
        const skuCodeCostPrice = productBySkuAndCostPriceMap[skuCode];
        let cost = 0;
        if (actionType === ACTION_TYPE.AGAIN) {
          cost = Number(skuCodeCostPrice) * Number(multiplier);
        } else if (actionType === ACTION_TYPE.AGAIN_BY_REDUCE_FIXED) {
          cost = parseFloat(
            (Number(skuCodeCostPrice) - Number(multiplier)).toFixed(2)
          );
        }
        if (cost && skuCodeCurrency && skuCodeCostPrice) {
          sku_cost_info_list.push({
            last_cost: skuCodeCostPrice,
            last_currency: skuCodeCurrency,
            currency: skuCodeCurrency,
            cost,
            sku_code: skuCode,
          });
        }
      }
    }
    if (isSkip) {
      skipCount++;
    } else if ([ACTION_TYPE.AGREE, ACTION_TYPE.REFUSE].includes(actionType)) {
      let discuss_audit_type = actionType === ACTION_TYPE.AGREE ? 1 : 2;
      successTotal++;
      paramList.push({
        discuss_sn: bargain_sn,
        document_sn,
        discuss_audit_type,
      });
    } else if (AGAIN_VALUE_LIST.includes(actionType)) {
      if (sku_cost_info_list.length) {
        paramList.push({
          discuss_sn: bargain_sn,
          document_sn,
          discuss_step,
          file_upload_list: [],
          reason: "",
          skc_name,
          sku_cost_info_list,
        });
        successTotal++;
      } else {
        skipCount++;
      }
    }
  }

  if (!paramList.length) {
    return { paramsList: [], successTotal, skipCount };
  }
  const filed =
    actionType === ACTION_TYPE.AGAIN
      ? "create_cost_discusses"
      : "confirm_infos";
  const paramsList = chunkArray(paramList, 500).map((item) => {
    return {
      [filed]: item,
    };
  });
  return { paramsList, successTotal, skipCount };
};

export default {
  getCurrentPage,
  getPageSize,
  getTotalPageSize,
  getProductBySkuMap,
  formatSaveParams,
  getDoAgreeToNegotiateUrl,
};
